package cn.edu.swu.shopcar;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.io.Writer;
import java.util.*;

@WebServlet("/cartBooks")
public class cartBooks extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session= req.getSession(false);
        shoppingCar shoppingCar= (cn.edu.swu.shopcar.shoppingCar)session.getAttribute("shoppingCar");
        Map<Integer, CarItem> map;
        map=shoppingCar.getMap();
        List<CarItem> carItems=new ArrayList<>();
        for(CarItem carItem: map.values()){
            carItems.add(carItem);
        }
        ObjectMapper objectMapper=new ObjectMapper();
        String json=objectMapper.writeValueAsString(carItems);
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        try(Writer writer=resp.getWriter()){
            writer.write(json);
        }
    }
}
